package itheima.zuoye.Test3;
import java.io.*;

public class CalculateExpressions {
    public static void main(String[] args) {
        String questionsFilePath = "D:\\javabasepro\\java AdvanceProject\\day11\\src\\itheima\\zuoye\\Test3\\questions.txt";
        String resultsFilePath = "D:\\javabasepro\\java AdvanceProject\\day11\\src\\itheima\\zuoye\\Test3\\results.txt";

        try {
            // 读取questions.txt文件内容
            BufferedReader reader = new BufferedReader(new FileReader(questionsFilePath));
            // 创建results.txt文件并写入结果
            BufferedWriter writer = new BufferedWriter(new FileWriter(resultsFilePath));

            String line;
            while ((line = reader.readLine()) != null) {
                // 解析表达式并计算结果
                String result = calculateExpression(line);
                // 将结果写入results.txt文件
                writer.write(result);
                writer.newLine();
            }

            reader.close();
            writer.close();
            System.out.println("计算完成，结果已写入results.txt文件。");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 解析表达式并计算结果
     * @param expression 表达式字符串
     * @return 计算结果的字符串
     */
    private static String calculateExpression(String expression) {
        // 找到运算符的位置
        int operatorIndex = -1;
        for (int i = 0; i < expression.length(); i++) {
            char c = expression.charAt(i);
            if (!Character.isDigit(c) && c != '+') {
                operatorIndex = i;
                break;
            }
        }

        if (operatorIndex == -1) {
            return "Invalid expression";
        }

        // 获取运算符
        char operator = expression.charAt(operatorIndex);

        // 切割字符串，转成数字
        String num1Str = expression.substring(0, operatorIndex).trim();
        String num2Str = expression.substring(operatorIndex + 1).trim();
        int num1 = Integer.parseInt(num1Str);
        int num2 = Integer.parseInt(num2Str);

        // 根据运算符进行相应的操作
        int result;
        switch (operator) {
            case '+':
                result = num1 + num2;
                break;
            case '-':
                result = num1 - num2;
                break;
            case '*':
                result = num1 * num2;
                break;
            case '/':
                if (num2 == 0) {
                    return "Division by zero";
                }
                result = num1 / num2;
                break;
            default:
                return "Invalid operator";
        }

        // 返回计算结果的字符串
        return expression + "=" + result;
    }
}


